package com.borqsprocessmanager.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.borqsprocessmanager.App;
import com.borqsprocessmanager.BatteryManager;
import com.borqsprocessmanager.Constant;
import com.borqsprocessmanager.IService;
import com.borqsprocessmanager.MainActivity;
import com.borqsprocessmanager.ProcessSettingManager;
import com.borqsprocessmanager.R;
import com.borqsprocessmanager.adapter.ProcessAdapter;
import com.borqsprocessmanager.info.ProcessStatsInfo;
import com.borqsprocessmanager.info.ReceiverProcessInfo;
import com.borqsprocessmanager.info.SectionInfo;
import com.borqsprocessmanager.util.CPUFreqSetting;
import com.borqsprocessmanager.util.Log;
import com.borqsprocessmanager.util.PreferencesUtil;
import com.borqsprocessmanager.view.sectionlistview.PinnedHeaderListView;
import com.borqsprocessmanager.view.sectionlistview.SectionListAdapter;

public class ProcessManagerFragment extends BaseFragment implements
        OnCheckedChangeListener {
    private final String TAG = "ProcessManagerFragment";

    private BatteryManager mBatteryManager;
    private View layout;
    // private ImageView mWhiteButton;
    private PinnedHeaderListView mListView;

    private PreferencesUtil mPreferencesUtil;

    private ArrayList<ReceiverProcessInfo> mApplist;
    private HashMap<String, ReceiverProcessInfo> mAutoStartMap, mDisableMap,
            mEnableMap;

    private boolean isCpufrep = false;
    private boolean isCpuFrepChanged = false;
    private boolean isDefinedCpuFrepMode = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        layout = inflater.inflate(R.layout.res_fragment, null);
        return layout;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        findView(layout);
        init();
        initData();
        // setAdapter(mList, mListView);
        // setAdapter(mApplist, mListView);
        setAdapter(mApplist, mListView);
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
        Log.v(TAG, "onPause");
        applyOrSaveRules();
        if (isCpuFrepChanged) {
            mPreferencesUtil.putBoolean(Constant.KAY_ISCPU_FREP, isCpufrep);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    /**
     * Apply or save iptable rules, showing a visual indication
     */
    private void applyOrSaveRules() {
        new Thread() {
            @Override
            public void run() {
                mBatteryManager.saveDisableMapForDB(MainActivity.isRoot,
                        mAutoStartMap, mDisableMap);
                mBatteryManager.saveEnablemapForDB(MainActivity.isRoot,
                        mAutoStartMap, mEnableMap);
            }
        }.start();
    }

    private void findView(View layout) {
        mListView = (PinnedHeaderListView) layout.findViewById(R.id.main_list);
    }

    private void init() {
        mPreferencesUtil = PreferencesUtil.getInstance(App.mContext);
        isCpufrep = mPreferencesUtil.getBoolean(Constant.KAY_ISCPU_FREP);
        isDefinedCpuFrepMode = mPreferencesUtil
                .getBoolean(Constant.KAY_ISDEFINED_CPU_FREP_STATE);
        isCanCpufreq();
    }

    private void initData() {
        mDisableMap = new HashMap<String, ReceiverProcessInfo>();
        mEnableMap = new HashMap<String, ReceiverProcessInfo>();
        try {
            if (!mActivity.isRoot) {
                Toast.makeText(mActivity, "请获得Root以获得更多功能", Toast.LENGTH_SHORT)
                        .show();
            }
            mAutoStartMap = ProcessSettingManager
                    .getCompoentProcessMap("android.net.conn.CONNECTIVITY_CHANGE");
            Log.v(TAG, "mAutoStartMap.size()===" + mAutoStartMap.size());
            mApplist = ProcessSettingManager.getProcesslist(mActivity.isRoot,
                    mAutoStartMap, mBatteryManager.mActionMap);
            Log.v(TAG, "mApplist.size===" + mApplist.size());
            insertIteam(mApplist);
            // if (mList == null) {
            // android.util.Log.v(TAG, "mList == null");
            // try {
            // mList = processSetManager
            // .getProcesslist("android.net.conn.CONNECTIVITY_CHANGE");
            // mActivity.mService.setReceiverInfo(mList);
            // } catch (NameNotFoundException e) {
            // e.printStackTrace();
            // }
            // }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void insertIteam(ArrayList<ReceiverProcessInfo> mApplist) {
        ReceiverProcessInfo newInfo = new ReceiverProcessInfo();
        newInfo.setAppName(getString(R.string.cpu_data));
        newInfo.setType(ReceiverProcessInfo.CPU_SETTING);
        newInfo.setSection(newInfo.head_cpu_setting);
        if (isCpufrep) {
            newInfo.setIsClose(1);
        } else {
            newInfo.setIsClose(0);
        }
        mApplist.add(0, newInfo);
    }

    private void isCanCpufreq() {
        if (isDefinedCpuFrepMode) {
            Log.v(TAG, "isCanCpufreq");
            CPUFreqSetting cpufreqSetting = new CPUFreqSetting();
            List<String> cpuGovers = cpufreqSetting.readCpuGovernors();
            cpufreqSetting.getCpuCurGovernor();
            for (String cpuGover : cpuGovers) {
                Log.v(TAG, "cpuGover===" + cpuGover);
                if (cpuGover.equals(CPUFreqSetting.POWER_SAVE_GOVERNOR)) {
                    mPreferencesUtil.putBoolean(
                            Constant.KAY_ISCPU_HAVE_USERSAPCE, true);
                    break;
                }
            }
            mPreferencesUtil.putBoolean(Constant.KAY_ISDEFINED_CPU_FREP_STATE,
                    true);
        }
    }

    @Override
    public void onBindServiced(IService personService,
            HashMap<String, ReceiverProcessInfo> actionMap,
            HashMap<String, ProcessStatsInfo> whiteMap) {
        super.onBindServiced(personService, actionMap, whiteMap);
        mBatteryManager = new BatteryManager(actionMap);
    }

    private void setAdapter(ArrayList<ReceiverProcessInfo> list,
            PinnedHeaderListView listView) {

        // mWhiteButton = (ImageView) header.findViewById(R.id.pro_head_white);

        ProcessAdapter adapter = new ProcessAdapter(App.mContext, list);
        // mItemAdapter = new DroidWallAdapter(App.mContext, list);
        SectionListAdapter sectionAdapter = new SectionListAdapter(adapter,
                R.id.droid_heade);
        adapter.setOnCheckedChanged(this);
        // listView.setFocusable(true);
        listView.addHeaderView(mActivity.getLayoutInflater().inflate(
                R.layout.process_list_head, null));
        listView.setAdapter(sectionAdapter);
        listView.setOnScrollListener(sectionAdapter);
        // listView.setPinnedHeaderView(mActivity.getLayoutInflater().inflate(
        // R.layout.item_head, listView, false));
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // ReceiverProcessInfo info = mAutoStartList.get((Integer)
        // buttonView.getTag());
        ReceiverProcessInfo info = mApplist.get((Integer) buttonView.getTag());
        android.util.Log.v(TAG, "onCheckedChanged");

        if (info.type == ReceiverProcessInfo.CPU_SETTING) {
            Log.v(TAG, "onCheckedChanged___" + ReceiverProcessInfo.CPU_SETTING);
            isCpuFrepChanged = true;
            isCpufrep = isChecked;
            // CPUFreqSetting cpuFreqSetting = new CPUFreqSetting();
            // cpuFreqSetting.setUserSpaceMod(CPUFreqSetting.TAG_USERSPACE);
        } else {
            if (isChecked) {
                Log.v(TAG, "mEnableMap");
                info.isClose = ReceiverProcessInfo.OPEN;
                mEnableMap.put(info.packageName, info);
                mDisableMap.remove(info.appName);
            } else {
                info.isClose = ReceiverProcessInfo.CLOSE;
                Log.v(TAG, "mDisableMap");
                mDisableMap.put(info.packageName, info);
                mEnableMap.remove(info.appName);
            }
        }
    }

    @Override
    protected void dismisListViewItem(int position) {
        // Animation shake = AnimationUtils.loadAnimation(App.mContext,
        // R.anim.scale);
        // mWhiteButton.startAnimation(shake);
    }

    // private void HandleProcess(HashMap<String, ReceiverProcessInfo> map,
    // boolean action) {
    // Iterator<Entry<String, ReceiverProcessInfo>> iter = map.entrySet()
    // .iterator();
    // while (iter.hasNext()) {
    // Map.Entry entry = (Map.Entry) iter.next();
    // ReceiverProcessInfo info = (ReceiverProcessInfo) entry.getValue();
    // Log.v(TAG, info.appName + "");
    // ProcessSettingManager.operatingAplacation(info.reivever, action);
    // }
    // }

    // private HashMap<String, ReceiverProcessInfo> getAutoStartAppMap(
    // HashMap<String, ReceiverProcessInfo> autoStartMap,
    // HashMap<String, ReceiverProcessInfo> anotherMap) {
    // HashMap<String, ReceiverProcessInfo> res = new HashMap<String,
    // ReceiverProcessInfo>();
    // Set<String> sets = anotherMap.keySet();
    // for (String key : sets) {
    // if (autoStartMap.containsKey(key)) {
    // res.put(key, autoStartMap.get(key));
    // }
    // }
    // return anotherMap;
    // }
    // private void saveDisableMapForDB(
    // HashMap<String, ReceiverProcessInfo> mDisableMap,
    // HashMap<String, ReceiverProcessInfo> mEnableMap) {
    // ArrayList<String> deleteKeyLists = new ArrayList<String>();
    // ArrayList<ContentValues> addLists = new ArrayList<ContentValues>();
    //
    // HashMap<String, ReceiverProcessInfo> curAction =
    // mActivity.mService.actionMap;
    // Set<String> dSet = mDisableMap.keySet();
    // Set<String> eSet = mEnableMap.keySet();
    //
    // for (String key : eSet) {
    // curAction.remove(key);
    // deleteKeyLists.add(key);
    // Log.v(TAG, "delete_AppName=" + key);
    // }
    // for (String key : dSet) {
    // curAction.put(key, mDisableMap.get(key));
    // ContentValues cv = new ContentValues();
    // ReceiverProcessInfo info = mDisableMap.get(key);
    // cv.put(ActionTable.PROCESS_NAME, info.processName);
    // cv.put(ActionTable.APPNAME, info.appName);
    // cv.put(ActionTable.PKG_NAME, info.packageName);
    // cv.put(ActionTable.ACATION_TYPE, info.isClose);
    // addLists.add(cv);
    // }
    // if (addLists.size() > 0) {
    // ContentValues[] values = new ContentValues[addLists.size()];
    // addLists.toArray(values);
    // mActivity.getContentResolver().bulkInsert(ActionTable.CONTENT_URI,
    // values);
    // Log.v(TAG, "addLists.size() >0===" + values.length);
    // }
    // if (deleteKeyLists.size() > 0) {
    // String[] selectionArgs = new String[deleteKeyLists.size()];
    // deleteKeyLists.toArray(selectionArgs);
    // for (String processname : deleteKeyLists) {
    // mActivity.getContentResolver().delete(ActionTable.CONTENT_URI,
    // ActionTable.PROCESS_NAME + "=?",
    // new String[] { processname });
    // }
    // Log.v(TAG, "deleteLists.size() >0===" + selectionArgs.length);
    // }
    // }
}
